using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;
using UwinEducation.Shared.Models;

namespace UwinEducation.Infrastructure.Repositories
{
    public class TermRepository : Repository<Term, Guid>, ITermRepository
    {
        public TermRepository(ApplicationDbContext context) : base(context)
        {
        }

        public async Task<PagedResult<Term>> GetPagedListAsync(TermPageRequest pageRequest)
        {
            var query = _context.Terms.AsQueryable();

            //if (!string.IsNullOrEmpty(pageRequest.Search))
            //{
            //    query = query.Where(t => t.Name.Contains(pageRequest.Search));
            //}
            if (!string.IsNullOrEmpty(pageRequest.Name))
                query = query.Where(t => t.Name.Contains(pageRequest.Name));
            if (!string.IsNullOrEmpty(pageRequest.ShortName))
                query = query.Where(t => t.ShortName.Contains(pageRequest.ShortName));
            if (!string.IsNullOrEmpty(pageRequest.Remarks))
                query = query.Where(t => t.Remarks.Contains(pageRequest.Remarks));

            var total = await query.CountAsync();
            var items = await query
                .OrderByDescending(t => t.CreatedAt)
                .Skip((pageRequest.PageIndex - 1) * pageRequest.PageSize)
                .Take(pageRequest.PageSize)
                .ToListAsync();

            return new PagedResult<Term>
            {
                Total = total,
                Items = items
            };
        }

        public async Task<Term> GetDetailsByIdAsync(Guid id)
        {
            return await _context.Terms
                .FirstOrDefaultAsync(t => t.Id == id);
        }

        public async Task<bool> ExistsByNameAsync(string name, Guid? excludeId = null)
        {
            return await _context.Terms
                .Where(t => t.Name == name && (!excludeId.HasValue || t.Id != excludeId.Value))
                .AnyAsync();
        }
    }
} 